package cn.tianyigps.tianyigpsapiv2.service;

import cn.tianyigps.tianyigpsapiv2.dao.EquipmentConfigDao;
import cn.tianyigps.tianyigpsapiv2.exception.PermissionDeniedException;
import cn.tianyigps.tianyigpsapiv2.oauth2.context.ClientPrincipal;
import cn.tianyigps.tianyigpspublic.bean.EquipmentConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiuHao
 * @Descirption:
 * @Date: 2019/4/26_17:24
 */
@Service
public class EquipmentConfigService {

    @Autowired
    private EquipmentConfigDao equipmentConfigDao;

    public void set(String equipmentId, String key, String value) throws PermissionDeniedException {
        EquipmentConfig equipmentConfig = equipmentConfigDao.findByEquipmentId(equipmentId);
        if(equipmentConfig == null){
            equipmentConfig = new EquipmentConfig();
            equipmentConfig.setClientId(ClientPrincipal.getClientId());
            equipmentConfig.setCreateTime(new Date());
            equipmentConfig.setEquipmentId(equipmentId);
            equipmentConfig.setConfig(new HashMap());
            equipmentConfig.setSubscriber(new HashMap<>());
        }
        Map config = equipmentConfig.getConfig();
        config.put(key,value);
        equipmentConfig.setUpdateTime(new Date());
        equipmentConfigDao.save(equipmentConfig);
    }

    public String get(String equipmentId, String key) {
        EquipmentConfig equipmentConfig = equipmentConfigDao.findByEquipmentId(equipmentId);
        if(equipmentConfig == null){
            return null;
        }
        Map config = equipmentConfig.getConfig();
        return (String) config.get(key);
    }

    public boolean del(String equipmentId, String key) {
        EquipmentConfig equipmentConfig = equipmentConfigDao.findByEquipmentId(equipmentId);
        if(equipmentConfig == null){
            return false;
        }
        Map config = equipmentConfig.getConfig();
        config.remove(key);
        equipmentConfigDao.save(equipmentConfig);
        return true;
    }

    public Map list(String equipmentId) {
        EquipmentConfig equipmentConfig = equipmentConfigDao.findByEquipmentId(equipmentId);
        if(equipmentConfig == null){
            return null;
        }
        Map config = equipmentConfig.getConfig();
        return config;

    }
}
